package com.chenl.consumer.interceptor;


import com.chenl.consumer.util.MDCUtils;
import com.chenl.consumer.util.TtlThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        System.out.println("来咯");
        String traceId = request.getHeader("traceId");
        String traceIdKey="traceId";
        if (traceId!=null){
            log.info("注入请求头中的traceID~~~");
            MDC.put(traceIdKey,traceId);
            return true;
        }
        log.info("注入新生成的的traceID~~~");
        traceId= MDCUtils.mdc();
//        request.setAttribute(traceIdKey,traceId);
        MDC.clear();
        MDC.put(traceIdKey,traceId);
        TtlThreadLocal.set(MDC.getCopyOfContextMap());//利用阿里的TTL设置上下文对象供子线程传递
        return true;
    }
}